import yaml
import os
from .log_utils import logger
from common.setting import ensure_path_sep
import jsonpath
from utils.faker_utils import FakerUtil
from utils.http_utils import HttpClient
import re


def read_config():
    """读取公共配置文件"""
    config_path = ensure_path_sep("\\common\\config.yaml")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    except FileNotFoundError:
        logger.error("未找到 config.yaml 文件，请检查路径。")
        return {}


def send_request(api, host, token):
    """发送 HTTP 请求并返回响应数据"""
    method = api.get("method")
    path = api.get("path")
    headers = api.get("headers", {})
    headers["Authorization"] = token
    data = api.get("data", {})
    url = f"{host}{path}"
    return HttpClient.send_request(method, url, headers=headers, data=data)


def replace_placeholders(obj, extracted_values):
    if isinstance(obj, str):
        for field, value in extracted_values.items():
            placeholder = f"${field}$"
            if placeholder in obj:
                obj = obj.replace(placeholder, str(value))
        return obj
    elif isinstance(obj, dict):
        new_dict = {}
        for key, val in obj.items():
            new_dict[key] = replace_placeholders(val, extracted_values)
        return new_dict
    elif isinstance(obj, list):
        new_list = []
        for item in obj:
            new_list.append(replace_placeholders(item, extracted_values))
        return new_list
    return obj


def call_faker_function(func_str):
    """调用 FakerUtil 类中的函数"""
    match = re.match(r"FakerUtil\.(\w+)(?:\((.*)\))?", func_str)
    if match:
        func_name = match.group(1)
        args_str = match.group(2)
        if hasattr(FakerUtil, func_name):
            func = getattr(FakerUtil, func_name)
            if args_str:
                args = [eval(arg.strip()) for arg in args_str.split(",")]
                return func(*args)
            else:
                return func()
    return func_str


def replace_faker_placeholders(obj):
    """替换 YAML 中的 FakerUtil 函数调用"""
    if isinstance(obj, str):
        if obj.startswith("FakerUtil."):
            return call_faker_function(obj)
        return obj
    elif isinstance(obj, dict):
        new_dict = {}
        for key, val in obj.items():
            new_dict[key] = replace_faker_placeholders(val)
        return new_dict
    elif isinstance(obj, list):
        new_list = []
        for item in obj:
            new_list.append(replace_faker_placeholders(item))
        return new_list
    return obj


def read_api_yamls(token):
    """读取 data 文件夹下所有 API 配置文件，并添加 token 到头部"""
    api_configs = []
    data_dir = ensure_path_sep("\\data_api")
    config = read_config()
    # 获取当前激活的环境配置
    active_env = config.get("active_env")
    env_config = config.get("environments", {}).get(active_env, {})
    host = env_config.get("host")
    if not host:
        logger.error(f"未找到环境 {active_env} 的host配置")
        return []
    if os.path.exists(data_dir):
        all_api_configs = {}
        for filename in os.listdir(data_dir):
            if filename.endswith(".yaml"):
                file_path = os.path.join(data_dir, filename)
                try:
                    with open(file_path, "r", encoding="utf-8") as f:
                        api_config = yaml.safe_load(f)
                        all_api_configs[filename.split(".")[0]] = api_config
                except Exception as e:
                    logger.error(f"读取 {file_path} 文件时出错: {e}")

        for name, api_config in all_api_configs.items():
            api = api_config.get("api", {})
            is_run = api.get("is_run", False)
            if is_run:
                headers = api.get("headers", {})
                headers["Authorization"] = token
                api["headers"] = headers

                # 替换 FakerUtil 函数调用
                api = replace_faker_placeholders(api)

                depends_on = api.get("depends_on") if isinstance(api, dict) else None
                if depends_on:
                    depend_api_config = all_api_configs.get(depends_on)
                    if depend_api_config:
                        depend_api = depend_api_config.get("api") if isinstance(depend_api_config, dict) else None
                        use_extract = api.get("use_extract", []) if isinstance(api, dict) else []
                        # 每次都重新发送依赖请求，确保数据的独立性
                        response_data = send_request(depend_api, host, token)
                        extracted_values = {}
                        for extract_item in use_extract:
                            for field, json_path_expr in extract_item.items():
                                result = jsonpath.jsonpath(
                                    response_data, json_path_expr
                                )
                                if result:
                                    extracted_values[field] = result[0]
                                else:
                                    logger.warning(
                                        f"未提取到 {field} 的值，JSONPath 表达式: {json_path_expr}"
                                    )
                        api = replace_placeholders(
                            api, extracted_values
                        )  # 确保更新 api 对象

                api_config["api"] = api  # 更新 api_config 中的 api 对象
                api_configs.append(api_config)
    return api_configs
